/**
 * Created by zhulizhe on 2017/8/30.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    TextInput,
    StyleSheet,
    Button,
    ScrollView
} from 'react-native';
import Constant from '../Contant'
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import Ionicons from 'react-native-vector-icons/Ionicons';
import LinearGradient from "react-native-linear-gradient";
import {GradientButton} from "../component/Button";
import RequestUtil from "../util/NetUtil";
const TOTALCOUNT = 60 ;
import loginStore from '../store/LoginStore'
import NumberUtil from "../util/NumberUtil";

const Input = ({value,placeholder,onChangeText,keyboardType='default',secureTextEntry=false})=>{
    return <View style={[{padding:15,backgroundColor:'#fff'},styles.borderBottom]}>
        <TextInput
            clearTextOnFocus={true}
            style={{fontSize:16,fontWeight:'400'}}
            value={value}
            keyboardType={keyboardType}
            secureTextEntry={secureTextEntry}
            placeholder={placeholder}
            onChangeText={onChangeText}/>
    </View>
}

const Header = ({navigation,title})=>{
    return <LinearGradient
            colors={['#14c2fc', '#399cfc']}
            style={{height:80,paddingTop:20,flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
        <View style={{flex:1}}>
                <TouchableOpacity
                    onPress={()=>{
                        navigation.goBack();
                    }}
                    style={{backgroundColor:'#00000000',paddingHorizontal:20}}
                    activeOpacity={0.8}>
                    <Ionicons name="ios-close-outline" color="#fff"  size={40}/>
                </TouchableOpacity>
            </View>
            <View style={{flex:2}}>
                <Text style={{
                    fontSize:Constant.FONT_SIZE_36,
                    backgroundColor:'#00000000',
                    fontWeight:'500',
                    color:'#fff',
                    alignSelf:'center'
                }}>{title}</Text>
            </View>
        <View style={{flex:1}}/>
        </LinearGradient>
}

const Footer = ()=>{
    return <View style={{padding:15}}>
        <Text>登录即为同意<Text style={{color:Constant.BLUECOLOR}}>《汇贝软件许可及服务协议》</Text></Text>
    </View>
}

@observer
export default class Login extends Component{

    @observable phoneNum = '' ;
    @observable decoratePhoneNum = '' ;

    @observable checkCode = '' ;

    @observable remainCount = TOTALCOUNT ;
    @observable waiting = false ;

    static navigationOptions = ({navigation}) =>({
        header:<Header navigation={navigation} title="登录"/>,
        headerStyle:{
            backgroundColor:'#00000000'
        }
    })

    constructor(props){
        super(props)
        this.goBack= this.goBack.bind(this);
    }

    // 开始倒计时
    startCount(){
        if(this.waiting)return ;
        if(this.phoneNum.length!=13)return ;
        let phone = NumberUtil.removeDecoratePhoneNumber(this.phoneNum) ;
        // 在此请求发送验证码
        RequestUtil.requestData('checkCode/login',{
            phoneNum:phone
        }).then((result)=>{
            this.waiting = true ;
            this.timer = setInterval(()=>{
                this.remainCount -= 1 ;
                if(this.remainCount == 0){
                    this.remainCount = TOTALCOUNT ;
                    this.waiting = false ;
                    this.clearTimer();
                }
            },1000) ;
        })
    }

    // 清除倒计时
    clearTimer(){
        this.timer && clearInterval(this.timer) ;

    }

    goBack(){
        this.props.navigation.goBack();

    }

    // 登录
    login(){
        RequestUtil.requestData('login/user',{
            checkCode:this.checkCode,
            phoneNum:NumberUtil.removeDecoratePhoneNumber(this.decoratePhoneNum)
        }).then((resp)=>{
            console.log('登录' + JSON.stringify(resp));
            if(resp == undefined)return ;
            loginStore.save(this.phoneNum,resp.access_token,resp.access_secret);
            this.goBack();
        })
    }

    render(){
        return <ScrollView style={{flex:1,backgroundColor:Constant.GRAYBGCOLOR}}>
            <View style={{flexDirection:'row',alignItems:'center',backgroundColor:'#fff'}}>
                <View style={{flex:3}}>
                    <Input
                        keyboardType="phone-pad"
                        placeholder="手机号"
                        value={this.decoratePhoneNum}
                        onChangeText={(text)=>{
                            this.phoneNum = text;
                            this.decoratePhoneNum = text.replace(/(\d{3})(\d{4})/,"$1-$2-") ;
                        }}/>
                </View>
                <View style={{flex:1,alignItems:'center'}}>
                    <View style={{alignItems:'center'}}>
                        <TouchableOpacity
                            onPress={this.startCount.bind(this)}
                            activeOpacity={0.8}
                            style={{
                            alignItems:'center',
                            justifyContent:'center',
                            backgroundColor:this.decoratePhoneNum.length==13&&!this.waiting  ? Constant.BLUECOLOR : Constant.TEXT_COLOR_F3,
                            height:30,
                            width:90,
                            borderRadius:4
                        }}>
                            <Text style={{
                                color:this.decoratePhoneNum.length==13&&!this.waiting ? '#fff' : Constant.TEXT_COLOR_9,
                                fontSize:Constant.FONT_SIZE_28
                            }}>{this.waiting ?this.remainCount +'s后重试' : '获取验证码'}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
            <View>
                <Input
                    placeholder="验证码"
                    onChangeText={(text)=>{
                        this.checkCode = text ;
                    }}/>
            </View>
            <View style={{height:40,paddingHorizontal:15,marginTop:30}}>
                <GradientButton
                    onPress={this.login.bind(this)}
                    title="登录"/>
            </View>
            <Footer/>
        </ScrollView>
    }
}

const styles = {
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    },
}


